import React, { useRef, useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout'
import { Button, Avatar, message, Drawer, Switch, Modal } from 'antd';
import { PlusOutlined, UserOutlined } from '@ant-design/icons';
import { connect } from 'dva'

import MusicAPI from '@/services/ant-design-pro/music';
import ProTable from '@ant-design/pro-table';
import m_config from '@/config/config'

import Create from './components/Music/Create'
import Edit from './components/Music/Edit'

const { getMusicList, deleteMusic, isLockMusic, findMusicLyricList } = MusicAPI
const Music = (props) => {
    const actionRef = useRef(); // 表格ref，便于自定义操作表格
    const { dispatch } = props;
    const [isModalEdit, setIsModalEdit] = useState(false),
        [isModalAdd, setIsModalAdd] = useState(false),
        [editData, setEditData] = useState(undefined),
        [data, setData] = useState({});

    useEffect(() => { // 初始化时执行
        setParams()
    }, []);

    // 获取歌手、专辑、曲作家、词作家选项值
    const setParams = (params) => {
        let keys = ['Singer', 'LyricAuthor', 'MelodyAuthor', 'Album'];
        for (let i in keys) {
            dispatch({
                type: 'music/refreshSelect',
                payload: {
                    key: keys[i]
                }
            });
        }
    }
    /**
     * 设置音乐数据到state
     * @returns obj(音乐列表)
     */
    const setMusicData = async () => {
        const result = await getMusicList();
        setData(result.data.value);
        return {
            data: result.data.value,
            success: true
        }
    }
    const delMusic = async (record) => {
        const result = await deleteMusic(record)
        if (result.status == 'ok') {
            await setMusicData();
            actionRef.current.reload();
            message.success("删除成功");
        } else {
            message.error('删除失败：' + result.data.message);
            console.log(result.data.error);
        }
    }
    /**
     * 控制模态框显示与隐藏
     */
    const isShowModalEdit = async (show, record = undefined) => {
        if (record) {
            let result = await findMusicLyricList({
                lyric_id: record.lyric_id
            })
            record.lyric = result.data.value[0].lyric
            setEditData(record);
        }
        setIsModalEdit(show);
    };

    const isShowModalAdd = (show) => {
        setIsModalAdd(show);
    };
    // 是否锁定：1正常 -1锁定
    const updateMusicLock = async (record) => {
        let result = await isLockMusic({
            music_id: record.music_id,
            is_lock: record.is_lock,
        });
        if (result.status = 'ok') {
            message.success('操作成功')
        } else {
            message.error('操作成功')
        }
    }
    /**
     * 获取音乐列表
     * @param {obj} params 搜索参数
     * @returns obj(音乐列表)
     */
    const getData = (params) => {
        if (JSON.stringify(data) != "{}") {
            let result = data;
            let music_name = params.music_name || "",
                singer_name = params.singer_name || "";
            if (music_name.trim().length > 0 || singer_name.trim().length > 0) {
                result = data.filter((item, index) => {
                    if (music_name && singer_name) {
                        return item.music_name.toLowerCase().indexOf(music_name.toLowerCase()) >= 0
                            && item.singer_name.toLowerCase().indexOf(singer_name.toLowerCase()) >= 0
                    } else if (music_name) {
                        return item.music_name.toLowerCase().indexOf(music_name.toLowerCase()) >= 0
                    } else if (singer_name) {
                        return item.singer_name.toLowerCase().indexOf(singer_name.toLowerCase()) >= 0
                    }
                })
            }
            return {
                data: result,
                success: true
            }
        }
        return setMusicData();
    }
    const columns = [
        {
            title: '音乐封面',
            dataIndex: 'music_cover_src',
            hideInSearch: true,
            render: (_, record) => (
                <Avatar
                    src={m_config.local + record.music_cover_src + record.music_cover_name}
                    size={64}
                    shape="square"
                    icon={<UserOutlined />}
                />
            )
        },
        {
            title: '音乐名',
            dataIndex: 'music_name',
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '此项为必填项',
                    },
                ],
            },
        },
        {
            title: '歌手',
            dataIndex: 'singer_name',
        },
        {
            title: '词作家',
            hideInSearch: true,
            dataIndex: 'lyric_author_name',
        },
        {
            title: '曲作家',
            hideInSearch: true,
            dataIndex: 'melody_author_name',
        },
        {
            title: '专辑',
            hideInSearch: true,
            dataIndex: 'album_name',
        },
        {
            title: '发行时间',
            hideInSearch: true,
            dataIndex: 'music_issue_time',
        }, {
            title: '是否禁用',
            dataIndex: 'is_lock',
            hideInSearch: true,
            // className: 'islock',
            sorter: (a, b) => a.is_lock - b.is_lock,
            render: (_, record) => (
                <Switch checkedChildren="启用"
                    unCheckedChildren="禁用"
                    defaultChecked={record.is_lock === -1}
                    onChange={() => {
                        record.is_lock = record.is_lock === -1 ? 1 : -1;
                        updateMusicLock(record);
                    }} />
            )
        },
        {
            title: '操作',
            valueType: 'option',
            render: (text, record, _, action) => [
                <a rel="noopener noreferrer" key="edit" onClick={() => isShowModalEdit(true, record)}>
                    编辑
                </a>,
                <a rel="noopener noreferrer" key="del" onClick={() => delMusic(record)}>
                    删除
                </a>,
            ],
        },
    ];

    return (
        <PageContainer>
            <div>
                <ProTable columns={columns} actionRef={actionRef} request={(params = {}, sort, filter) => {
                    return getData(params);
                }}
                    rowKey="music_id"
                    search={{
                        labelWidth: 'auto'
                    }} pagination={{
                        pageSize: 5,
                    }}
                    dateFormatter="string" headerTitle="高级表格" toolBarRender={() => [
                        <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => isShowModalAdd(true)}>
                            新建
                        </Button>,
                    ]} />
            </div>

            {/* <Modal
                title="修改音乐"
                width="1110px"
                height="593px"
                footer={false} placement="right"
                visible={isModalEdit}
                onCancel={() => isShowModalEdit(false)}
                // destroyOnClose={true}
            > */}
            <Edit
                visible={isModalEdit}
                isShowModal={isShowModalEdit}
                actionRef={actionRef}
                setUserData={setMusicData}
                initData={editData}
            />
            {/* </Modal> */}

            <Drawer
                title="添加音乐"
                width="600px"
                footer={false}
                visible={isModalAdd}
                onClose={() => isShowModalAdd(false)}
                destroyOnClose={true}>
                <Create
                    visible={isModalAdd}
                    isShowModal={isShowModalAdd}
                    actionRef={actionRef}
                    setUserData={setMusicData}
                />
            </Drawer>
        </PageContainer>
    )
}

export default connect(({ music }) => ({ music }))(Music);